﻿namespace DataDuctus.MongoDb.Serialization.Extensions
{
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Reflection;
	using System.Runtime.Serialization;

	internal static class KnownTypeExtractExtensions
	{
		internal static IEnumerable<Type> ToKnownTypes(this Type type)
		{
			var knownAttrs = type.GetAttributes<KnownTypeAttribute>();

			var list = new List<Type>();

			foreach (var attr in knownAttrs)
			{
				if (null != attr.Type)
				{
					if (!list.Contains(attr.Type))
					{
						list.Add(attr.Type);
					}

					continue;
				}

				var types =
					(IEnumerable<Type>)
					type.InvokeMember(
						attr.MethodName,
						BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod,
						null,
						null,
						null);

				foreach (var t in types.Where(t => !list.Contains(t)))
				{
					list.Add(t);
				}
			}

			return list;
		}

		internal static bool IsKnownTypesRootType(this Type type)
		{
			var parentType = type.BaseType;

			if (null != parentType.GetAttribute<DataContractAttribute>())
			{
				return false;
			}

			return null != type.GetAttribute<KnownTypeAttribute>();
		}
	}
}